// #include<iostream>
// #include<thread>
// #include<pthread.h>

// void threadrun(int n)
// {
//     std::cout<<" i am a new thread "<<n<<std::endl;
// }

// void* func(void*t)
// {
//     std::cout<<"当前是新线程"<<std::endl;
//     return nullptr;
// }

// int main()
// {
//     //std::thread t1(threadrun,10);
//     //t1.join();
//     pthread_t id;
//     pthread_create(&id,nullptr,func,nullptr);
//     std::cout<<id<<std::endl;
//     return 0;
// }

//多线程抢票
#include<iostream>
#include<pthread.h>
#include<string>
#include<vector>
#include<string.h>
#include<unistd.h>
#include<mutex>

const int N = 4;
int tickets=1000;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void* function(void* argc)
{
    char*name=(char*)argc;
    int*sum=new int;
    *sum=0;
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(tickets>0)
        {
            usleep(1000);
            tickets--;
            std::cout<<name<<":"<<tickets<<std::endl;
            (*sum)++;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    delete[] name;
    return sum;
}

int main()
{
    std::vector<pthread_t>thread;
    for(int i=0;i<N;i++)
    {
        std::string name("thread");
        name+=std::to_string(i);
        char*buffer=new char[64];
        memcpy(buffer,name.c_str(),sizeof(buffer));
        pthread_t id;
        pthread_create(&id,nullptr,function,(void*)buffer);
        thread.push_back(id);
    }
    //等待
    for(int i=0;i<N;i++)
    {
        void*ret;
        pthread_join(thread[i],&ret);
        std::cout<<*((int*)ret)<<std::endl;
        delete (int*)ret;
    }
    return 0;
}